<template>
  <div>
    <!-- first - 交付经理填写项目交付信息 -->
    <div class="desc-item">
      <div class="form-item">项目交付信息</div>
      <DynamicDescription
        ref="dynamicDescription"
        :descriptions="projectDeliveryDetails.projectDeliveryInfoDesc"
        :descriptForm="projectDeliveryDetails.projectDeliveryInfoForm"
        :readOnly="!isShowApprovalOperation('first')"
        :column="2"
      />
      <div v-if="projectFiles[processStageName].length > 0">
        <div class="table-title">上传附件</div>
        <FilesUpload
          ref="filesUploadRef"
          :fileTypes="projectFiles[processStageName]"
          :projectInfo="projectInfo"
          :readOnly="!isShowApprovalOperation('first')"
          @getProjectFilesInfo="$emit('getProjectFilesInfo')"
        />
      </div>
      <div v-if="isShowApprovalOperation('first')">
        <div class="form-item">审批信息</div>
        <div v-if="!isPureConstructionMode">
          <div class="table-title" > 下一环节 - 服务经理审批 </div>
          <DynamicDescription
            :descriptions="projectDeliveryDetails.projectDeliverySecondInfoDesc"
            :readOnly="true"
            :column="1"
          />
          <ApprovalOpinion
            ref="approvalOpinionRef"
            v-model="approvalOpinionData" 
            required 
            label="审批意见"
          />
          <div class="mb-16 flex">
            <el-button
              class="ml-auto"
              type="primary"
              size="default"
              @click="approvalProcess('agree', 'projectManager', projectInfo.maintenance_manager_id)"
            >同意</el-button>
          </div>
        </div>
        <div v-else>
          <div class="table-title" > 下一环节 - 建设单位部门经理审批 </div>
          <DynamicDescription
            :descriptions="projectDeliveryDetails.projectDeliveryThirdInfoDesc"
            :readOnly="true"
            :column="1"
          />
          <ApprovalOpinion
            ref="approvalOpinionRef"
            v-model="approvalOpinionData" 
            required 
            label="审批意见"
          />
          <div class="mb-16 flex">
            <el-button
              class="ml-auto"
              type="primary"
              size="default"
              @click="approvalProcess('agree', 'projectManager', projectInfo.construction_department_manager_id)"
            >同意</el-button>
          </div>
        </div>
      </div>

      <!-- second - 服务经理审批 -->
      <div v-if="isShowApprovalOperation('second')">
        <div class="form-item">审批信息</div>
        <div class="table-title"> 下一环节 - 建设单位部门经理审批 </div>
        <DynamicDescription
          :descriptions="projectDeliveryDetails.projectDeliveryThirdInfoDesc"
          :readOnly="true"
          :column="1"
        />  
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData"
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
              class="ml-auto"
              type="danger"
              size="default"
              @click="approvalProcess('refuse', 'maintenanceManager', projectInfo.construction_department_manager_id)"
            >驳回</el-button>
            <el-button
              type="primary"
              size="default"
              @click="approvalProcess('agree', 'maintenanceManager', projectInfo.construction_department_manager_id)"
            >同意</el-button>
        </div>
      </div>

      <!-- third - 建设单位部门经理审批 -->
      <div v-if="isShowApprovalOperation('third')">
        <div class="form-item">审批信息</div>
        <div class="table-title"> 下一环节 - 省端项目主管审批 </div>
        <DynamicDescription
          :descriptions="projectDeliveryDetails.projectDeliveryFourthInfoDesc"
          :readOnly="true"
          :column="1"
        />
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData"
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
              class="ml-auto"
              type="danger"
              size="default"
              @click="approvalProcess('refuse', 'constructionDepartmentManager', projectInfo.project_supervisor_id)"
            >驳回</el-button>
            <el-button
              type="primary"
              size="default"
              @click="approvalProcess('agree', 'constructionDepartmentManager', projectInfo.project_supervisor_id)"
            >同意</el-button>
        </div>
      </div>

      <!-- fourth - 省端项目主管审批 -->
      <div v-if="isShowApprovalOperation('fourth')">
        <div class="form-item">审批信息</div>
        <div class="table-title"> 下一环节 - ICT系统审批 </div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData"
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
              class="ml-auto"
              type="danger"
              size="default"
              @click="approvalProcess('refuse', 'projectSupervisor', 0)"
            >驳回</el-button>
            <el-button
              type="primary"
              size="default"
              @click="approvalProcess('agree', 'projectSupervisor', 0)"
            >同意</el-button>
        </div>
      </div>

      <!-- fifth - ICT系统审批 -->

      <!-- sixth - 交付经理审核 -->
      <div v-if="isShowApprovalOperation('sixth')">
        <div class="form-item">审批信息</div>
        <div class="table-title"> 下一环节 - 政企运维平台审批 </div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData"
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <!-- 交付阶段给到dict后交付经理不能再驳回 -->
            <el-button
              class="ml-auto"
              type="primary"
              size="default"
              @click="approvalProcess('agree', 'projectManagerSecond', 0)"
            >同意</el-button>
        </div>
      </div>

      <!-- seventh - 政企运维平台审批 -->

    </div>
  </div>
</template>

<script setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import DynamicDescription from '@/views/project/projectDetails/components/DynamicDescription.vue'
import FilesUpload from '@/views/project/projectDetails/components//FilesUpload.vue';
import { ref, toRefs } from 'vue'
import { formatDate } from '@/utils/formatTime'
import ApprovalOpinion from '../../components/ApprovalOpinion.vue';

// emit事件合集
const emit = defineEmits(['getApprovalProcess', 'getProjectInfo', 'getProjectFilesInfo']);

// Props传值
const props = defineProps({
  isShowApprovalOperation: Function,
  projectInfo: Object,
  projectDeliveryDetails: Object,
  processStageName: String,
  taskName: String,
  role: String,
  processList: Array,
  projectFiles: Object
})
const { isShowApprovalOperation, projectInfo, projectDeliveryDetails, processStageName, taskName, role, processList } = toRefs(props);

// const isPureConstructionMode = ref(projectInfo.value.construction_mode === '纯建设')
const isPureConstructionMode =false

// 动态详情组件ref对象
const dynamicDescription = ref()
// 审批意见
const approvalOpinionData = ref('同意')
const approvalOpinionRef = ref()
// 创建对文件上传子组件的引用
const filesUploadRef = ref(null);

const approvalProcess = async (result, currentRole, nextRoleId) => {
  try {
    if (result === 'agree') {
      await Promise.all([
        dynamicDescription.value.validateForm(),
        approvalOpinionRef.value.validateForm()
      ])
      if (isShowApprovalOperation.value('first') && filesUploadRef.value && !filesUploadRef.value?.validateFiles()) {
        return;
      }
    } else {
      await approvalOpinionRef.value.validateForm()
    }
    // 表单验证通过，执行提交逻辑
    ElMessageBox.confirm(`是否${result === 'agree' ? '同意' : '驳回'}该流程单？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {

      if (result === 'agree') {
        const agreeProcessData = {
          assignedUserIds: [nextRoleId],
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '同意',
          copyUserIds: [],
          variables: {}
        }
        
        if (currentRole === 'projectManager') {
          const approvalFormData = dynamicDescription.value.getFormData()
          projectInfo.value = Object.assign(projectInfo.value, approvalFormData)
          
          projectInfo.value.maintenance_start_time_owner = formatDate(projectInfo.value.maintenance_start_end_time_owner[0], "YYYY-MM-DD")
          projectInfo.value.maintenance_end_time_owner = formatDate(projectInfo.value.maintenance_start_end_time_owner[1], "YYYY-MM-DD")
          projectInfo.value.maintenance_start_time_si = formatDate(projectInfo.value.maintenance_start_end_time_si[0], "YYYY-MM-DD")
          projectInfo.value.maintenance_end_time_si = formatDate(projectInfo.value.maintenance_start_end_time_si[1], "YYYY-MM-DD")
        }

        if (['projectManager', 'maintenanceManager', 'constructionDepartmentManager'].includes(currentRole)) {
          const agreeData = {
            update: true,
            project_index_do: projectInfo.value,
            task_approve_req_vo: agreeProcessData
          }
          await IctApi.agreeProjectProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        } else if (currentRole === 'projectSupervisor'){
          const agreeData = {
            update: true,
            project_index_do: projectInfo.value,
            task_approve_req_vo: agreeProcessData
          }
          await IctApi.agreeProjectDeliverySupervisorProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        } else if (currentRole === 'projectManagerSecond') {
          const agreeData = {
            update: true,
            project_index_do: projectInfo.value,
            task_approve_req_vo: agreeProcessData
          }
          await IctApi.agreeProjectDeliveryManagerSecondProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        }

      } else if (result === 'refuse') {
        const refuseData = {
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '不同意'
        }
        await IctApi.refuseProjectDeliveryProcess(refuseData).then(() => {
          emit('getApprovalProcess')
        })
      }
      ElMessage({
        type: 'success',
        message: '提交成功'
      })
    })
  } catch (error) {
    console.log("🚀 ~ approvalProcess ~ error:", error)
    ElMessage({
      type: 'error',
      message: '请按照格式要求填写信息'
    })
  }
  
}

</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

</style>